package com.woniuxy.homepage.core.util;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.woniuxy.homepage.core.constant.PromotionConstant;
import com.woniuxy.homepage.core.mapper.CarGoodsActivityMapper;
import com.woniuxy.homepage.core.model.CarGoodsActivity;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Date: 2021/7/5:9:37  <br/>
 * Description: 往缓存里边添加活动商品
 */

@Component
public class ActivityJob {

    @Resource
    private CarGoodsActivityMapper carGoodsActivityMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0/5 * * * * ?")
    public void initActivityProduct(){

        //查询在活动时间内的商品
        List<CarGoodsActivity> list = carGoodsActivityMapper.selectByTimeAndStatus();
        for (CarGoodsActivity activity : list){
            Long time = DateUtil.between(new Date(),activity.getEndTime(), DateUnit.HOUR);
            for (int i=0 ; i<activity.getTotal(); i++){
                redisTemplate.opsForList().rightPush("activity:count:"+activity.getId(),activity.getGoodsId());
            }
            redisTemplate.expire("activity:count:"+activity.getId(),time, TimeUnit.HOURS);
            carGoodsActivityMapper.updateStatue(activity.getId(), PromotionConstant.START_STATUS);

        }

        //改变目前时间大于活动结束的商品的状态
        List<CarGoodsActivity> list2 = carGoodsActivityMapper.selectByTime();
        for (CarGoodsActivity goods : list2) {
            carGoodsActivityMapper.updateStatue(goods.getId(), PromotionConstant.OVER_STATUS);
        }

    }

}
